import React , { useEffect , useState } from 'react';
import { getPlants } from '../api/home.js';

const Home = () => {
    const [plants,setPlants] = useState([]);
    useEffect(() => {
        //调用封装好的接口函数
        getPlants().then(res => {
            setPlants(res.data.result.plantList);
        })
    },[]);

    const collect = (plant,isCancel)=>{
        if(plant.isCollect && (!isCancel)){
            return alert('您已收藏')
        }
        setPlants(
            plants.map(item=>{
                if(item.plantID === plant.plantID){
                    return {...item,isCollect:!item.isCollect}
                }
                return item;
            })
        )
    };

    return (
        <div>
            <h2>收藏列表</h2>
            <div>
                {
                    plants.filter(item=>item.isCollect)
                        .map(plant=>{
                            return (
                                <div key={plant.plantID}>
                                    {plant.name}
                                    <button
                                        onClick={()=>collect(plant,"cancel")}
                                    >取消收藏</button>
                                </div>
                            )
                        })
                }
            </div>
            <h2>鲜花列表</h2>
            <div>
                {
                    plants.map(item => {
                        return <div key={item.plantID}>
                            <img src={item.coverURL} alt={item.name} />
                            <p>{item.name}</p>
                            <p>{item.engName}</p>
                            <p>{item.area?item.area:'未知产地'}</p>
                            <button onClick={() => collect(item)}>
                                {
                                    item.isCollect?'已收藏':'收藏'
                                }
                            </button>
                        </div>
                    })
                }
            </div>
        </div>
    )
};

export default Home;